﻿using AliyunDDNS.Core;
using System;
using System.Configuration;
using System.Net;
using System.ServiceProcess;
using System.Threading.Tasks;
//using System.Text;
//using System.Threading;
//using System.Threading.Tasks;

namespace AliyunDDNS.HeartbeatService
{
    public partial class HeartbeatService : ServiceBase, IDisposable
    {
        //private Timer _timer;
        private int frequency;
        private string targetURL;
        private string tokenKey;
        private System.Timers.Timer task;


        public HeartbeatService()
        {
            InitializeComponent();

            var _frequency = ConfigurationManager.AppSettings["TransmitFrequency"] ?? "60000";
            int.TryParse(_frequency, out frequency);
            targetURL = ConfigurationManager.AppSettings["TargetURL"] ?? "";
            tokenKey = ConfigurationManager.AppSettings["TokenKey"] ?? "";

            ServicePointManager.DefaultConnectionLimit = 10;
        }

        protected override void OnStart(string[] args)
        {
            task = new System.Timers.Timer(frequency);   //实例化Timer类，设置间隔时间；   
            task.Elapsed += new System.Timers.ElapsedEventHandler(OnSendHttp); //到达时间的时候执行事件；   
            task.AutoReset = true;   //设置是执行一次（false）还是一直执行(true)；   
            task.Enabled = true;     //是否执行System.Timers.Timer.Elapsed事件；
            task.Start();
        }


        protected override void OnStop()
        {
            if (task != null)
            {
                task.Close();
                task.Dispose();
                task = null;
            }
        }
        public new void Dispose()
        {
            Stop();
            base.Dispose();
        }

        public void OnSendHttp(object source, System.Timers.ElapsedEventArgs e)
        {
            Task.Run(() => SendHttp());
        }

        private async void SendHttp()
        {
            GC.Collect();

            var token = Guid.NewGuid().ToString().Replace("-", "").ToLower();
            var userAgent = DdnsHelper.ComposeToken(token, tokenKey);
            HttpWebRequest request = WebRequest.Create(targetURL + token) as HttpWebRequest;
            request.Method = "GET";
            request.UserAgent = userAgent;
            request.KeepAlive = false;
            request.AllowAutoRedirect = false;
            

            //request.Timeout = 30000;

            HttpWebResponse response = null;
            try
            {
                response = await request.GetResponseAsync() as HttpWebResponse;
                var cntentLength = response.ContentLength;
            }
            catch {
                //
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response.Dispose();
                    response = null;
                }
            }
        }
    }
}
